package com.yxw.blog.controller;

import com.yxw.blog.annotation.UnInterception;
import com.yxw.blog.bean.entity.User;
import com.yxw.blog.service.LoginService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * @author yexinwei
 */
@Api(value = "用户登录控制层")
@Controller
public class LoginController {

    @Autowired
    LoginService loginService;

//    @UnInterception
//    @RequestMapping({"/","/index"})
//    public String index(){
//        return "index";
//    }

    @ApiOperation(value = "登录接口")
    @UnInterception
    @PostMapping("/login")
    public String login(@RequestParam("name") @ApiParam(value = "用户名") String name , @RequestParam("password")  @ApiParam(value = "密码") String password, Model model , HttpSession session){
        User user = loginService.login(name, password,session);
        if(user!=null) {
            model.addAttribute("name",user.getUserDisplayName());
            String portraitUrl = user.getUserPortrait();
            String headName = portraitUrl.substring(portraitUrl.lastIndexOf("\\")+1,portraitUrl.length());
            String head = "/img/head/"+headName;
            model.addAttribute("head",head);
            return "myblog";
        }else{
            model.addAttribute("info","账号或密码不存在");
            return "index";
        }
    }

    @UnInterception
    @RequestMapping("/logout")
    public String toLogin(HttpSession session){
        //session过期
        session.invalidate();
        return "index";
    }
}
